package com.hengshan.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.IdUtil;
import com.hengshan.common.ResultBody;
import com.hengshan.common.enums.RedisKey;
import com.hengshan.common.utils.RedisUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 验证码操作处理
 */
@RestController
public class CaptchaController {

    /**
     * 生成验证码
     */
    @RequestMapping("/captchaImage")
    public ResultBody getCode() {
        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        // ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(150, 40, 5, 4);
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(120, 40, 1, 20);
        // 存入redis并设置过期时间为10分钟
        RedisUtil.set(RedisKey.CAPTCHA_KEY + uuid, captcha.getCode(), 10);
        String base64String = "data:image/png;base64," + captcha.getImageBase64();
        Map<String, Object> resp = new HashMap<>();
        resp.put("uuid", uuid);
        resp.put("img", base64String);
        return ResultBody.success(resp);
    }

}
